﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class Star : EventTrigger
{
    private RectTransform mRectTransform { get; set; }
    private int randomX { get; set; }
    private int randomY { get; set; }
    public int starMoveSpeed { get; set; }
    private int starScore { get; set; }
    private bool disappear { get; set; }

    private void Start()
    {
        randomX = Random.Range(-300, 180);
        randomY = Random.Range(150, -180);
        starMoveSpeed = 1;
        starScore = 50;
        disappear = false;

        //在顶部随机生成出场位置
        mRectTransform = this.GetComponent<RectTransform>();
        mRectTransform.anchoredPosition = new Vector2(randomX, 290);
    }

    public override void OnPointerDown(PointerEventData eventData)
    {
        //点击阳光
        Text monoyText = GameObject.Find("Money").transform.Find("Text").GetComponent<Text>();
        //获取现在的金币数
        int monoyCount = int.Parse(monoyText.text);
        //显示出来
        monoyText.text = (monoyCount + starScore).ToString();
        //使该ui处于无法激活状态
        this.GetComponent<Image>().raycastTarget = false;
        //逐渐消失
        disappear = true;
    }


    private void Update()
    {
        //从顶部降落下来
        if (mRectTransform.anchoredPosition.y != randomY)
        {
            mRectTransform.anchoredPosition = new Vector2(mRectTransform.anchoredPosition.x, Mathf.Lerp(mRectTransform.anchoredPosition.y, randomY, Time.deltaTime * starMoveSpeed));
            if (Mathf.Abs(mRectTransform.anchoredPosition.y - randomY) < 1.0f)
            {
                mRectTransform.anchoredPosition = new Vector2(mRectTransform.anchoredPosition.x, randomY);
            }
        }
        //消失
        if (disappear)
        {
            CanvasGroup cg = this.GetComponent<CanvasGroup>();
            if (cg.alpha != 0)
            {
                cg.alpha = Mathf.Lerp(cg.alpha, 0, Time.deltaTime);
                if (Mathf.Abs(cg.alpha) <= 0.1f)
                {
                    cg.alpha = 0;
                    disappear = false;
                }
            }
        }
    }
}
